using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.ComponentModel;
using WebPart=System.Web.UI.WebControls.WebParts.WebPart;

namespace zevenseas.Community.Web.UI.WebControls.WebParts
{
    public class ChoiceFilter : WebPart, ITransformableFilterValues, IWebEditable
    {
        private string listId = "";
        private string choiceFieldId = "";
        private RadioButtonList choiceRadioList;
        private DropDownList choiceDropDown;
        private int columns = 3;
        private ChoiceFilterDisplayType displayType;

        [WebBrowsable(false), WebDisplayName("Display Type")]
        [Personalizable(PersonalizationScope.Shared), SPWebCategoryName("Choice Settings")]
        [DefaultValue(ChoiceFilterDisplayType.RadioButton)]
        public ChoiceFilterDisplayType DisplayType
        {
            get { return displayType; }
            set { displayType = value; }
        }
        
        [WebBrowsable(false), WebDisplayName("Columns")]
        [Personalizable(PersonalizationScope.Shared), SPWebCategoryName("Choice Settings")]
        [DefaultValue(3)]
        public int Columns
        {
            get { return columns; }
            set { columns = value; }
        }

        [WebBrowsable(false), WebDisplayName("List Display Name")]
        [Personalizable(PersonalizationScope.Shared), SPWebCategoryName("Choice Settings")]
        [DefaultValue("")]
        public string ListId
        {
            get { return listId; }
            set
            {
                listId = value;
            }
        }

        [WebBrowsable(false), WebDisplayName("Choice Property Display Name")]
        [Personalizable(PersonalizationScope.Shared), SPWebCategoryName("Choice Settings")]
        [DefaultValue("")]
        public string ChoiceFieldId
        {
            get { return choiceFieldId; }
            set
            {
                choiceFieldId = value;
            }
        }

        #region ITransformableFilterValues Members

        public bool AllowAllValue
        {
            get { return true; }
        }

        public bool AllowEmptyValue
        {
            get { return false; }
        }

        public bool AllowMultipleValues
        {
            get { return false; ; }
        }

        public string ParameterName
        {
            get { return "Choice Value"; }
        }

        public ReadOnlyCollection<string> ParameterValues
        {
            get
            {
                if (choiceRadioList == null || choiceDropDown == null)
                    return null;

                string[] values;
                if (choiceRadioList.Visible)
                {
                    values =  new []{choiceRadioList.SelectedValue};
                }
                else
                {
                    values = new[] { choiceDropDown.SelectedValue };                    
                }
                
                if (string.IsNullOrEmpty(values[0]))
                    return null;
                else
                    return new ReadOnlyCollection<string>(values);
            }
        }

        [ConnectionProvider("Choice Filter", "ITransformableFilterValues", AllowsMultipleConnections = true)]
        public ITransformableFilterValues SetConnectionInterface()
        {
            return this;
        }

        protected override void OnPreRender(EventArgs e)
        {
            if (displayType == ChoiceFilterDisplayType.DropDownList)
            {
                if (choiceDropDown != null)
                {
                    choiceDropDown.Visible = true;
                    choiceRadioList.Visible = false;
                }
            }
            else
            {
                if (choiceRadioList != null)
                {
                    choiceRadioList.Visible = true;
                    choiceDropDown.Visible = false;
                }
            }

            base.OnPreRender(e);
        }

        protected override void CreateChildControls()
        {
            SPFieldMultiChoice choiceField;
            SPList blogList;

            try
            {
                blogList = SPContext.Current.Web.Lists[new Guid(listId)];
                choiceField = (SPFieldMultiChoice)blogList.Fields[new Guid(ChoiceFieldId)];
            }
            catch (System.Exception)
            {
                Literal configWebPart = new Literal();
                configWebPart.Text = "To configure this web part, <a href=" + GetToolPaneLink() +
                                     ">open the tool pane</a> and then select the List and Choice Column";                
                Controls.Add(configWebPart);
                return;
            }

            ListItem choiceButton;
            choiceButton = new ListItem();
            choiceButton.Text = "All";
            choiceButton.Value = "";

            choiceRadioList = new RadioButtonList();
            choiceRadioList.RepeatColumns = Columns;
            choiceRadioList.AutoPostBack = true;
            choiceRadioList.Items.Add(choiceButton);
            choiceRadioList.AppendDataBoundItems = true;
            choiceRadioList.DataSource = choiceField.Choices;
            choiceRadioList.DataBind();
            choiceRadioList.Visible = false;

            choiceDropDown = new DropDownList();
            choiceDropDown.AutoPostBack = true;
            choiceDropDown.Items.Add(choiceButton);
            choiceDropDown.AppendDataBoundItems = true;
            choiceDropDown.DataSource = choiceField.Choices;
            choiceDropDown.DataBind();
            choiceDropDown.Visible = false;
            
            if (string.IsNullOrEmpty(choiceRadioList.SelectedValue))
                choiceRadioList.SelectedValue = "";

            Controls.Add(choiceRadioList);
            Controls.Add(choiceDropDown);

            base.CreateChildControls();
        }

        #endregion

        protected string GetToolPaneLink()
        {
            bool hasRights = ((ISecurableObject)SPContext.Current.Web).DoesUserHavePermissions((SPBasePermissions)Microsoft.SharePoint.SPPermissionGroup.WebDesigner);

            if (!hasRights)
                return "Web Part has not been configured";

            string editLink = ToolPane.GetShowExtensibleToolPaneEvent(string.Format(@"'{0}'", this.UniqueID));
            editLink = string.Format(@"javascript:{0}", editLink.Replace(@"ExtensibleView", @"Edit"));
            return editLink;
        } 


        #region IWebEditable Members

        EditorPartCollection IWebEditable.CreateEditorParts()
        {
            List<EditorPart> editors = new List<EditorPart>();

            EditorPart choiceColumnEditor = new ChoiceFilterEditor();
            choiceColumnEditor.ID = "ChoiceColumnEditor" + this.ID;

            editors.Add(choiceColumnEditor);
            return new EditorPartCollection(editors);
        }

        object IWebEditable.WebBrowsableObject
        {
            get { return this; }
        }

        #endregion
    }
}